package org.example.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.collections4.CollectionUtils;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author wxm
 * @date 2025/2/14 16:07
 */
public class ExcelExportUtils {
    /**
     * 导出Excel
     *
     * @param headList  Excel表头列表
     * @param dataList  Excel内容列表
     * @param sheetName Excel工作表名称
     * @param fileName  文件名
     * @param response  响应对象
     * @throws IOException
     */
    public static void exportExcel(List<String> headList, List<LinkedHashMap<String, Object>> dataList, String sheetName, String fileName, HttpServletResponse response)
            throws IOException {
        // 清理文件名中的非法字符
        if (fileName == null || fileName.trim().isEmpty()) {
            fileName = sanitizeFileName(sheetName + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        } else {
            fileName = sanitizeFileName(fileName);
        }

        try (OutputStream servletOutputStream = response.getOutputStream()) {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8) + ".xlsx");

            // 创建一个 WriteSheet 对象
            WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();

            // 处理表头
            List<List<String>> head = new ArrayList<>();
            if (!CollectionUtils.isEmpty(headList)) {
                headList.forEach(headName -> head.add(Collections.singletonList(headName)));
            }

            // 处理数据
            List<List<String>> data = new ArrayList<>();
            if (!CollectionUtils.isEmpty(dataList)) {
                dataList.forEach(map -> {
                    List<String> list = new ArrayList<>();
                    for (String title : headList) {
                        Object value = map.get(title);
                        list.add(value == null ? "" : value.toString());
                    }
                    data.add(list);
                });
            }

            // 使用 EasyExcel 进行写入操作
            EasyExcel.write(servletOutputStream)
                    .head(head)
                    .sheet(sheetName)
                    .doWrite(data);
        } catch (IOException e) {
            throw new IOException("导出Excel时发生错误: " + e.getMessage(), e);
        }
    }

    private static String sanitizeFileName(String fileName) {
        return fileName.replaceAll("[^a-zA-Z0-9.-]", "_");
    }
}
